import asyncio
import websockets
import json
import threading
import logging
from .base_client import BaseChatClient

class WebClient(BaseChatClient):
    """Web聊天客户端"""

    def __init__(self):
        super().__init__()
        self.users = []
        self.message_callback = None
        self.file_callback = None
        self.system_message_callback = None
        self.user_list_callback = None
        self.error_callback = None
        self.connected_callback = None
        self.disconnected_callback = None

    def set_callbacks(self,
                     on_message=None,
                     on_file=None,
                     on_system_message=None,
                     on_user_list=None,
                     on_error=None,
                     on_connected=None,
                     on_disconnected=None):
        """设置回调函数"""
        self.message_callback = on_message
        self.file_callback = on_file
        self.system_message_callback = on_system_message
        self.user_list_callback = on_user_list
        self.error_callback = on_error
        self.connected_callback = on_connected
        self.disconnected_callback = on_disconnected

    async def on_connected(self):
        """连接成功时调用"""
        if self.connected_callback:
            self.connected_callback(f"成功连接到服务器 {self.server_address}")

    async def on_disconnected(self):
        """断开连接时调用"""
        if self.disconnected_callback:
            self.disconnected_callback("与服务器的连接已断开")

    async def on_text_message_received(self, formatted_message, sender, raw_message):
        """收到文本消息时调用"""
        if self.message_callback:
            self.message_callback(formatted_message, sender, raw_message)

    async def on_file_received(self, file_data):
        """收到文件时调用"""
        if self.file_callback:
            self.file_callback(file_data)

    async def on_system_message_received(self, formatted_message, raw_message):
        """收到系统消息时调用"""
        if self.system_message_callback:
            self.system_message_callback(formatted_message, raw_message)

    async def on_user_list_updated(self, users):
        """用户列表更新时调用"""
        self.users = users
        if self.user_list_callback:
            self.user_list_callback(users)

    async def on_message_sent(self, message):
        """消息发送成功时调用"""
        pass

    async def on_file_sent(self, filename):
        """文件发送成功时调用"""
        if self.message_callback:
            self.message_callback(f"文件 {filename} 已发送", "System", f"文件 {filename} 已发送")

    async def on_error(self, error_message):
        """发生错误时调用"""
        if self.error_callback:
            self.error_callback(error_message)

    def run(self, server_address, user_id, room_id="default"):
        """运行客户端（同步方法）"""
        # 在新线程中运行异步事件循环
        thread = threading.Thread(target=self._run_async, args=(server_address, user_id, room_id))
        thread.daemon = True
        thread.start()
        return thread

    def _run_async(self, server_address, user_id, room_id):
        """在新线程中运行异步事件循环"""
        # 创建新的事件循环
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)

        # 运行连接
        loop.run_until_complete(self.connect(server_address, user_id, room_id))

        # 保持事件循环运行
        try:
            loop.run_forever()
        except KeyboardInterrupt:
            pass
        finally:
            loop.close()

    def stop(self):
        """停止客户端"""
        async def _stop():
            await self.disconnect()

        # 在当前事件循环中运行停止操作
        try:
            loop = asyncio.get_event_loop()
            if loop.is_running():
                asyncio.create_task(_stop())
            else:
                loop.run_until_complete(_stop())
        except RuntimeError:
            # 没有事件循环时创建新的
            loop = asyncio.new_event_loop()
            loop.run_until_complete(_stop())
            loop.close()